package service

import (
	"tadmin/models"
	"tadmin/models/dto"
	"tadmin/pkg/orm"
	"time"
)

type WorkerService struct{}

// Query 字典查询
func (s *WorkerService) QueryByCardNo(cardNo string) (worker *dto.WorkerVO, err error) {
	db := orm.DB.Model(&models.Worker{})
	//查询条件
	if cardNo != "" {
		db = db.Where("card_no = ?", cardNo)
	}
	//查询数据
	err = db.First(&worker).Error
	if err != nil {
		return nil, err
	}

	return worker, err
}

func (s *WorkerService) ListWorkPlace() (workPlaceList []string, err error) {
	db := orm.DB.Model(&models.Worker{})
	//查询条件
	db.Distinct("DISTINCT(work_place)")
	//查询数据
	err = db.Scan(&workPlaceList).Error
	if err != nil {
		return nil, err
	}

	return workPlaceList, err
}

// Query 字典查询
func (s *WorkerService) PageQuery(query dto.WorkerQueryDto) ([]dto.WorkerVO, int64, error) {
	db := orm.DB.Model(&models.Worker{})
	var pageNum, pageSize = query.PageNum, query.PageSize

	//查询条件
	var name, cardNo, unit, place = query.Name, query.CardNo, query.WorkUnit, query.WorkPlace

	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}
	if cardNo != "" {
		db = db.Where("card_no LIKE ?", "%"+cardNo+"%")
	}
	if unit != "" {
		db = db.Where("work_unit LIKE ?", "%"+unit+"%")
	}
	if place != "" {
		db = db.Where("work_place LIKE ?", "%"+place+"%")
	}
	//总条数
	var total int64
	db.Count(&total)

	offset := (pageNum - 1) * pageSize
	//查询数据
	var list []dto.WorkerVO
	err := db.Order("id DESC").Offset(offset).Limit(pageSize).Find(&list).Error
	if err != nil {
		return nil, 0, err
	}

	return list, total, err
}

func (s *WorkerService) Delete(id int64) error {
	err := orm.DB.Delete(&models.Worker{}, "id = ?", id).Error
	return err
}

func (s *WorkerService) Add(addDto dto.WorkerAddDto) error {
	var worker = &models.Worker{
		Name:      addDto.Name,
		CardNo:    addDto.CardNo,
		WorkPlace: addDto.WorkPlace,
		WorkUnit:  addDto.WorkUnit,
		GmtCreate: time.Now(),
		GmtModify: time.Now(),
	}
	err := orm.DB.Create(worker).Error
	return err
}
